package com.tianliangedu.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DruidDBPoolUtil {
	private static DruidDBPoolUtil databasePool = null;
	private static DruidDataSource dds = null;
	static {
		Properties properties = loadPropertyFile("druid.properties");
		try {
			dds = (DruidDataSource) DruidDataSourceFactory
					.createDataSource(properties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private DruidDBPoolUtil() {
	}

	public static synchronized DruidDBPoolUtil getInstance() {
		if (null == databasePool) {
			databasePool = new DruidDBPoolUtil();
		}
		return databasePool;
	}

	public DruidPooledConnection getConnection() throws SQLException {
		return dds.getConnection();
	}

	public static Properties loadPropertyFile(String fullFile) {
		Properties p = new Properties();
		if (fullFile == "" || fullFile.equals("")) {
			System.out.println("属性文件为空!~");
		} else {
			// 加载属性文件
			InputStream inStream = DruidDBPoolUtil.class.getClassLoader()
					.getResourceAsStream(fullFile);
			try {
				p.load(inStream);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return p;
	}

	public static void main(String[] args) throws Exception {
		DruidDBPoolUtil dbp = DruidDBPoolUtil.getInstance();
		DruidPooledConnection con = dbp.getConnection();

		String sql = "SELECT * FROM tb_class_category";

		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			System.out.println(rs.getInt("id") + "," + rs.getString("name")
					+ "," + rs.getString("class_name"));
		}

		ps.close();
		con.close();
		dbp = null;
	}
}